import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:power_distribution_system/common/system_config.dart';
import 'package:provider/provider.dart';

import '../../bean/wirelesstm_bean.dart';
import '../../model/initapp_model.dart';
import '../../utils/tools/createwebsocket_tool.dart';
import '../../utils/tools/localstorage_tool.dart';
import '../../utils/tools/screenutil_tool.dart';
import '../../utils/widget/appbar_widget.dart';
import '../../utils/widget/fixedtip_widget.dart';
import '../../utils/widget/nodata_widget.dart';
import '../../viewmodel/wirelesstm_vm.dart';
import 'components/list_widget.dart';

class WirelesstmView extends StatefulWidget {
  @override
  WirelesstmViewState createState() => new WirelesstmViewState();
}

class WirelesstmViewState extends State<WirelesstmView> {

  // 页面是否完成加载
  bool isCompleteLoad = false;

  // 台区信息
  Map equipmentInfo;

  // 服务端响应的数据
  List<WirelesstmBean> pageData;

  // 存储ws对象
  MyWebSocket instanceWebSocket;

  // 存储ws定时器
  Timer wsTimer;

  // 网络状态
  bool networkstate;

  // 标记当前app的状态（特指：异常情况0：网络异常  1：WebSocket已断开   2：重连WebSocket）
  int componentState;

  // * 统计各项函数被执行的次数
  // 1、网络监听首次进入页面时为：false（无法网络是否通畅），将为执行未接通的“行为处理”。
  //   因WebSocket中有重连机制，当网络转为正常时会导致拿到数据且不断尝试重连的bug
  // 2、网络监听在builder函数中会被多次触发，但已有的函数都只需要执行一次。
  // 综上所属需要对组件执行次数进行统计并作为判断条件
  int implementCount = 0;

  // 标记是否正常关闭Websocket
  // 其中跳转路由属于正常关闭，其他均属于异常关闭
  bool normalShutdownWebsocket = false;


  @override
  Widget build(BuildContext context) {
    TextStyle textStyle = TextStyle(fontSize: SystemConfig.fs_title3);

    return Scaffold(
      appBar: AppBarWidget("无线无缘测温", isShowRI: false).build(context),
      body: Consumer<InitAppModel>(
        builder: (context,model,child) {
          // 将网络状态存储为全局状态，便于其他函数访问。（该状态会实时更新）
          networkstate = model.networkstate;

          // 必须保证网络通畅
          if(networkstate) {
            // 标记网络已恢复
            componentState = null;

            // 检查是否为初始化状态
            if(implementCount <= 0) {
              // 发起网络请求，获取页面数据
              initPage(context);

              // 开启WebSocket
              initWebSocket();

              // 统计执行次数
              implementCount++;
            }

          } else {
            // 标记网络异常
            componentState = 0;

            if(implementCount > 0 && !normalShutdownWebsocket) {
              // 还原组件初始化状态
              implementCount = 0;
            }
          }

          // 绘制组件
          return Container(
            width: double.infinity,
            child: Stack(
              children: [
                isCompleteLoad ? Container(
                  padding: EdgeInsets.only(
                    top: model.networkstate ? 0 : ST.seth(76),
                  ),
                  child: NestedScrollView(
                    headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                      return <Widget>[
                        SliverAppBar(
                          leading: null,
                          automaticallyImplyLeading:false,
                          backgroundColor: Theme.of(context).backgroundColor,
                          pinned: true,
                          flexibleSpace: Container(
                            height: ST.seth(108),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  width: ST.setw(275),
                                  alignment: Alignment.center,
                                  child: Text("时间",style: textStyle)
                                ),
                                Container(
                                  width: ST.setw(200),
                                  alignment: Alignment.center,
                                  child: Text("名称",style: textStyle)
                                ),
                                Container(
                                  width: ST.setw(135),
                                  alignment: Alignment.center,
                                  child: Text("温度",style: textStyle)
                                ),
                                Container(
                                  width: ST.setw(130),
                                  alignment: Alignment.center,
                                  child: Text("状态",style: textStyle)
                                ),
                              ],
                            ),
                          ),
                        ),
                      ];
                    },
                    body: SingleChildScrollView(
                      child: ListWidget(context, pageData),
                    ),
                  ),
                ) : NoData(),
                componentState == null ? SizedBox.shrink() : Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: FixedTopWidget(componentState),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 初始化页面
  /// * [context] 必填|上下文
  void initPage(BuildContext context) async {
    // 读取台区信息
    equipmentInfo = json.decode(await LocalStorage.getStringItem("equipmentInfo"));

    // 获取服务端数据
    List<WirelesstmBean> res = await new WirelessTmVM().getWirelessTmInfo(context,
      { "equipmentId" : equipmentInfo["equipmentId"] },
    );

    // 渲染页面
    if(res != null) {
      setState(() {
        componentState = null;
        isCompleteLoad = true;
        pageData = res;
      });
    } else {
      setState(() {
        isCompleteLoad = false;
      });
    }
  }


  /// 初始化WebSocket
  void initWebSocket() async {
    String token = await LocalStorage.getStringItem("token");
    String url = "equipmentTypeQuery/${token}/3/${equipmentInfo['equipmentId']}";

    instanceWebSocket = new MyWebSocket(url,
        onMessage: (dynamic result) {
          // 接通websocket数据后修改componentState
          if(componentState != null) {
            setState(() { componentState = null; });
          }

          // 将Websocket中获取的数据赋值pageData
          if(pageData != null && result != "pong") {
            print("收到数据了");
            List<WirelesstmBean> newWSData = [];
            result["data"].forEach((key, value) => newWSData.add(WirelesstmBean(key,value)));
            setState(() {
              pageData = newWSData;
            });
          }
        },
        onError: (error) => print("websocket错误了"),
        onDone: () {
          if(networkstate && !normalShutdownWebsocket && implementCount > 0) {
            // 标记websocket已经断开
            setState(() { componentState = 1; });

            // 设置5s重连
            wsTimer = Timer(Duration(seconds: 5), () {
              instanceWebSocket.openSocket();
            });

          }
        }
    );
  }


  @override
  void dispose() {
    super.dispose();

    normalShutdownWebsocket = true;

    if(wsTimer != null) wsTimer.cancel();

    if(instanceWebSocket != null) instanceWebSocket.closeSocket();

    implementCount = null;
  }


}